package com.example.myapplication3;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.awt.font.NumericShaper;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class RateListActivity3 extends ListActivity implements Runnable {
    private static final String TAG ="List3Activity" ;  //AppCompatActivity
    private ArrayList<HashMap<String,String>> listItems;//存放文字、图片
    Handler handler;
    private SimpleAdapter listItemAdapter;//适配器
    private int msgWhat=7;
    SimpleAdapter adapter1;

    private String logDate="";
    private final String DATE_SP_KEY="lastRateDateStr";
    private NumericShaper IOUtils=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences sp=getSharedPreferences("myrate", Context.MODE_PRIVATE);
        logDate=sp.getString(DATE_SP_KEY,"");
        Log.i("List","lastRateDateStr="+logDate);

        initListView();
        this.setListAdapter(listItemAdapter);
        MyAdapter adapter=new MyAdapter(this,R.layout.list_item,listItems);
        Thread t=new Thread(this);
        t.start();
        handler = new Handler() {
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == msgWhat) {
                    List<HashMap<String,String>> retList=(List<HashMap<String, String>>) msg.obj;
                    adapter1=new SimpleAdapter(RateListActivity3.this,retList,
                            R.layout.list_item,
                            new String[]{"ItemTitle","ItemDetail"},
                            new int[]{R.id.itemTitle,R.id.itemDetail});
                    setListAdapter(adapter1);
                    Log.i("handler","reset list...");
                }
                super.handleMessage(msg);
            }
        };
    }

    private void initListView() {
        listItems = new ArrayList<HashMap<String, String>>();
        for(int i=0;i<10;i++){
            HashMap<String,String>map=new HashMap<String,String>();//必须放在里面，map是多个
            map.put("ItemTitle","Rate:"+i);//标题文字
            Log.i(TAG,"rate"+i);
            map.put("ItemDetail","detatil:"+i);//详情描述
            listItems.add(map);
        }
        listItemAdapter=new SimpleAdapter(this,
                listItems,//listItem数据源
                R.layout.list_item,//Listitem的Xml布局，要有两个布局，一个是map的布局，还有一个本页面的布局
                new String[]{"ItemTitle","ItemDetail"},
                new int[]{R.id.itemTitle,R.id.itemDetail}
        );
    }
    @Override
    public void run() {
        Log.i("tread","run...");
        List<String> retList=new ArrayList<String>();
        Message msg=handler.obtainMessage();
        String curDateStr=(new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        Log.i("run","curDateStr"+"logDate:"+logDate);
        if(curDateStr.equals(logDate)){
            //如果相等则不从网络中获取数据
            Log.i("run","日期相等，从数据库中获得数据");
            DBManager dbManager=new DBManager(RateListActivity3.this);
            for(RateItem rateItem:dbManager.listAll()){
                retList.add(rateItem.getCurName()+"=>"+rateItem.getCurRate());
            }
        }else{
            Log.i("run","日期相等，从网络中获取数据");
            try{
                Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
                Elements tables = doc.getElementsByTag("table");
                Log.i(TAG, "run: "+doc.title());
                Element table6 = tables.get(1);
                Elements tds = table6.getElementsByTag("td");//Elements是一个集合
                List<RateItem> rateList=new ArrayList<RateItem>();
                for (int a = 0;a<tds.size();a+=8) {
                    if (tds.size() > 0) {
                        String str = tds.get(a).text();
                        Log.i(TAG, "run:td:" + str);
                        String val1 = tds.get(a+5).text();
                        Log.i(TAG, "run: rate:" + val1);
                        float val2=Float.parseFloat(val1);
                        val2=100/val2;
                        RateItem rateItem=new RateItem(str,val1);
                        rateList.add(rateItem);
                    }}
//                List<RateItem> rateList=new ArrayList<RateItem>();
//                URL url=new URL("https://www.boc.cn/sourcedb/whpj/");
//                HttpURLConnection httpConn=(HttpURLConnection) url.openConnection();
//                InputStream in=httpConn.getInputStream();
//                String retStr=IOUtils.toString(in,"gb2312");
//                Document doc=Jsoup.parse(retStr);
//                Elements tables = doc.getElementsByTag("table");
//                Element retTable = tables.get(5);
//                Elements tds = retTable.getElementsByTag("td");
//                int tbSize=tds.size();
//                for(int i=0;i<tbSize;i+=8){
//                    Element td1=tds.get(i);
//                    Element td2=tds.get(i+5);
//                    float val=Float.parseFloat(td2.text());
//                    val=100/val;
//                    RateItem rateItem=new RateItem(td1.text(),td2.text());
//                    rateList.add(rateItem);
//                }
                DBManager dbManager=new DBManager(RateListActivity3.this);
                dbManager.deleteAll();
                Log.i("db","删除所有记录");
                dbManager.addAll(rateList);
                Log.i("db","添加新记录");
            }catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
//更新纪录日期
            SharedPreferences sp=getSharedPreferences("myrate",Context.MODE_PRIVATE);
            SharedPreferences.Editor edit=sp.edit();
            edit.putString(DATE_SP_KEY,curDateStr);
            edit.commit();
            Log.i("run","更新日期结束"+curDateStr);
        }
        msg.obj=retList;
        msg.what=msgWhat;
        handler.sendMessage(msg);
    }
}